﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================

using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using XCI.Core;
using XCI.Helper;

namespace XCI.Sys
{
    public class SysWebApiClient : WebApiClient
    {
        public SysWebApiClient(WebApiConfig config) : base(config)
        {
        }


        /// <summary>
        /// 初始化默认请求头
        /// </summary>
        /// <param name="defaultRequestHeaders">默认请求头</param>
        public override void OnInitDefaultRequestHeaders(HttpRequestHeaders defaultRequestHeaders)
        {
            base.OnInitDefaultRequestHeaders(defaultRequestHeaders);

            defaultRequestHeaders.Add("os", $"Windows {App.ClientOsVersion}");
            defaultRequestHeaders.Add("browser", $"WinForm {App.ClientXCIVersion}");
            //defaultRequestHeaders.Add("devExpress", App.ClientDevExpressVersion);
            //defaultRequestHeaders.Add("xciCore", App.ClientXCIVersion);

            defaultRequestHeaders.Add("appId", App.Setting.Id);
            defaultRequestHeaders.Add("X-Requested-Type", "APIHttpRequest");
        }


        /// <summary>
        /// 发起Http请求之前触发
        /// </summary>
        /// <param name="request">Http请求对象</param>
        public override void OnBeforeRequest(HttpRequestMessage request)
        {
            base.OnBeforeRequest(request);
            if (SysApp.CurrentUser != null && !string.IsNullOrEmpty(SysApp.CurrentUser.Token))
            {
                request.Headers.Add("token", SysApp.CurrentUser?.Token);
            }

            var timestamp = DateTimeHelper.GetTimeStamp().ToString(CultureInfo.InvariantCulture);
            var appToken = StringHelper.Md5String(DateTimeHelper.FormatDate(DateTime.Now.Date, "*yyyy**MM***dd****") + App.Setting.Id + timestamp);
            request.Headers.Add("timestamp", timestamp);//时间戳
            request.Headers.Add("appToken", appToken);//appToken
        }
    }

    public class SysWebFileApiClient : SysWebApiClient
    {
        private const string UPLOAD_TOKEN_HEADER_KEY = "uploadToken";
        public SysWebFileApiClient(WebApiConfig config) : base(config)
        {
        }

        /// <summary>
        /// 发起Http请求之前触发
        /// </summary>
        /// <param name="request">Http请求对象</param>
        public override void OnBeforeRequest(HttpRequestMessage request)
        {
            base.OnBeforeRequest(request);
            request.Headers.Add(UPLOAD_TOKEN_HEADER_KEY, EncryptHelper.AESEncrypt(DateTimeHelper.FormatDate(DateTime.Now, "*yyyy**MM***dd****")));
        }
    }
}